package com.example.vueblog.security;

import cn.hutool.core.lang.TypeReference;
import cn.hutool.json.JSONUtil;
import com.alibaba.fastjson.JSON;
import com.example.vueblog.common.utils.JwtTokenUtil;
import com.example.vueblog.common.Result;
import com.example.vueblog.common.enums.ResultEnum;
import com.example.vueblog.entity.security.SelfUserDetails;
import org.springframework.beans.BeanUtils;
import org.springframework.security.core.Authentication;
import org.springframework.security.web.authentication.AuthenticationSuccessHandler;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.io.PrintWriter;
import java.util.Map;

/**
 * 用户登录成功返回
 *
 * @author yushunshun
 * @date 2022/5/28 17:55
 */
/*@Component
public class AjaxAuthenticationSuccessHandler implements AuthenticationSuccessHandler {
    @Override
    public void onAuthenticationSuccess(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, Authentication authentication) throws IOException, ServletException {
        //获取登录用户,生成token
        SelfUserDetails userDetails = (SelfUserDetails) authentication.getPrincipal();
        String token = JwtTokenUtil.generateToken(userDetails.getUsername(), JSONUtil.toBean(JSONUtil.toJsonStr(userDetails), new TypeReference<Map<String, Object>>() {
        }, true));

        httpServletResponse.setCharacterEncoding("utf-8");
        httpServletResponse.setContentType("application/json; charset=utf-8");

        httpServletResponse.setHeader("Authorization", "Bearer " + token);

        UserInfo info = new UserInfo();
        BeanUtils.copyProperties(userDetails, info);
        Result<Object> result = Result.ok(ResultEnum.USER_LOGIN_SUCCESS.getCode(), ResultEnum.USER_LOGIN_SUCCESS.getMessage(), info);
        PrintWriter writer = httpServletResponse.getWriter();
        writer.write(JSON.toJSONString(result));
    }
}*/
